<template>
	<image class="icon" :style="{ width: `${size || 18}px`, height: `${size || 18}px` }" :src="svgData"
		mode="scaleToFill" />
</template>

<script>
const fs = wx.getFileSystemManager()
export default {
	name: "icon",
	data() {
		return {
			svgCache: {},//缓存SVG内容
			svgData: null,
		};
	},
	props: {
		title: {
			type: String,
			default: '',
			required: true,
		},
		size: {
			type: String,
			default: '30',
		},
		color: {
			type: String,
			default: '#999',
		},
	},
	mounted() {
		// console.log(this.$svg[this.title]);
		this.getSvgFile(this.$svg[this.title]);
	},
	watch: {
		color(newVal) {
			let svgData = this.svgCache[this.$svg[this.title]];
			if (svgData && newVal) {
				let newFile = this.changeColor(svgData, newVal);
				this.svgData = that.svgToBase64(newFile)
			}
		}
	},
	methods: {
		getSvgFile(src) {
			let that = this;
			fs.readFile({
				filePath: src,
				encoding: 'UTF-8',
				position: 0,
				success(res) {
					let data = res.data;
					if (data) {
						if (data instanceof ArrayBuffer) {
							that.svgCache[src] = that.arrayBufferToStr(data);
						} else {
							that.svgCache[src] = data;
						}
						let newFile = that.changeColor(that.svgCache[src], that.color)
						that.svgData = that.svgToBase64(newFile);
					}
				},
				fail(res) {
					console.error(res)
				}
			})
		},
		changeColor(data, color) {
			// console.log(data);
			let newSvg;
			if (/fill=".*?"/.test(data)) {
				newSvg = data?.replace(/fill=".*?"/g, `fill="${color}"`);  // SVG有默认色
			} else {
				newSvg = data?.replace(/<svg /g, `<svg fill="${color}" `); // 无默认色
			}
			return newSvg
		},
		svgToBase64(svg) {
			const utf8 = new Uint8Array(svg.length);
			for (let i = 0; i < svg.length; i++) {
				utf8[i] = svg.charCodeAt(i);
			}
			// 使用Buffer进行Base64编码
			const base64 = wx.arrayBufferToBase64(utf8.buffer);
			// 返回带有data URI前缀的Base64字符串
			return 'data:image/svg+xml;base64,' + base64;
		},
		arrayBufferToStr(buffer) {
			let str = '';
			const uint8Array = new Uint8Array(buffer);
			for (let i = 0; i < uint8Array.length; i++) {
				str += String.fromCharCode(uint8Array[i]);
			}
			return str;
		}
	}
}
</script>